package action;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import table.User;
import table.UserHandle;

/**
 * 添加用户进入小组的控制器
 * 参数：userid, teamid
 * 将userid对应的用户的小组编号改为teamid
 * 返回xml文件，成功则result标签为OK，否则result标签为FAIL
 */
@WebServlet("/AddUserToTeam")
public class AddUserToTeam extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddUserToTeam() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 管理员登录有效性验证段
		User user = (User) request.getSession().getAttribute("user");
		if(user == null || !user.getGroup().equals("admin")){
			request.getRequestDispatcher("index.jsp").forward(request, response);
			return;
		}
		// 响应设置段
		response.setContentType("text/xml; charset=UTF-8");
		response.setHeader("Cache-Control","no-store");
		response.setHeader("Pragma","no-cache");
		response.setDateHeader("Expires",0);
		// 获取参数
		String userid = request.getParameter("userid");
		String tid = request.getParameter("teamid");
		int teamid = 0;
		try {
			teamid = Integer.parseInt(tid);
		} catch(Exception e) {
			response.getWriter().print("<root><result>FAIL</result></root>");
			return;
		}
		if(teamid > 32766 || teamid <= 0) {
			response.getWriter().print("<root><result>FAIL</result></root>");
			return;
		}		
		UserHandle handle = new UserHandle();
		User u = handle.getUserById(userid);
		u.setTeamid(teamid);
		if(handle.updateToDB(u.getId(), u)) {
			response.getWriter().print("<root><result>OK</result></root>");
		}else {
			response.getWriter().print("<root><result>FAIL</result></root>");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
